import { Controller, Get, Post, Logger, Param } from '@nestjs/common';
import { TradingService } from './trading/trading.service';
import { BinanceService } from './binance/binance.service';

@Controller()
export class AppController {
  private readonly logger = new Logger(AppController.name);

  constructor(
    private readonly tradingService: TradingService,
    private readonly binanceService: BinanceService,
  ) {}

  @Get()
  getStatus(): any {
    const tradingState = this.tradingService.getTradingState();
    const performanceMetrics = this.tradingService.getPerformanceMetrics();
    
    return {
      message: '🤖 AI自动交易系统',
      status: tradingState.isActive ? '运行中' : '已停止',
      tradingState,
      performanceMetrics,
      timestamp: new Date().toISOString(),
    };
  }

  @Post('start')
  async startTrading(): Promise<any> {
    try {
      await this.tradingService.startTrading();
      return {
        success: true,
        message: '自动交易系统已启动',
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error('启动交易系统失败:', error);
      return {
        success: false,
        message: '启动失败: ' + error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }

  @Post('stop')
  async stopTrading(): Promise<any> {
    try {
      await this.tradingService.stopTrading();
      return {
        success: true,
        message: '自动交易系统已停止',
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error('停止交易系统失败:', error);
      return {
        success: false,
        message: '停止失败: ' + error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }

  @Get('account')
  async getAccountInfo(): Promise<any> {
    try {
      const accountInfo = await this.binanceService.getAccountInfo();
      const positions = await this.binanceService.getPositions();
      
      return {
        success: true,
        data: {
          accountInfo,
          positions,
        },
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error('获取账户信息失败:', error);
      return {
        success: false,
        message: '获取账户信息失败: ' + error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }

  @Get('performance')
  getPerformance(): any {
    const performanceMetrics = this.tradingService.getPerformanceMetrics();
    const tradingState = this.tradingService.getTradingState();
    
    return {
      success: true,
      data: {
        performanceMetrics,
        tradingState,
      },
      timestamp: new Date().toISOString(),
    };
  }

  @Get('price/:symbol')
  async getPrice(@Param('symbol') symbol: string): Promise<any> {
    try {
      const price = await this.binanceService.getCurrentPrice(symbol);
      return {
        success: true,
        data: {
          symbol,
          price,
        },
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error(`获取${symbol}价格失败:`, error);
      return {
        success: false,
        message: `获取${symbol}价格失败: ` + error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }

  @Get('test-connection')
  async testConnection(): Promise<any> {
    try {
      const serverTime = await this.binanceService.getServerTime();
      return {
        success: true,
        data: {
          serverTime,
          message: '连接测试成功',
        },
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error('连接测试失败:', error);
      return {
        success: false,
        message: '连接测试失败: ' + error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }

  @Get('klines/:symbol/:interval')
  async getKlines(
    @Param('symbol') symbol: string,
    @Param('interval') interval: string,
  ): Promise<any> {
    try {
      this.logger.log(`获取K线数据: ${symbol}, 间隔: ${interval}`);
      const klineData = await this.binanceService.getKlineData(symbol, interval, 10);
      
      return {
        success: true,
        data: {
          symbol,
          interval,
          klines: klineData,
          count: klineData.length,
        },
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error(`获取${symbol}K线数据失败:`, error);
      return {
        success: false,
        message: `获取${symbol}K线数据失败: ` + error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }

  @Post('test-order')
  async testOrder(): Promise<any> {
    try {
      // 测试模拟下单 - 小额 BTCUSDT 市价买入
      const orderParams = {
        symbol: 'BTCUSDT',
        side: 'BUY' as 'BUY' | 'SELL',
        type: 'MARKET' as 'MARKET' | 'LIMIT' | 'STOP' | 'STOP_MARKET' | 'TAKE_PROFIT' | 'TAKE_PROFIT_MARKET',
        quantity: 0.001, // 小额测试
      };

      const result = await this.binanceService.placeOrder(orderParams);
      return {
        success: true,
        data: {
          message: '模拟下单测试成功',
          order: result,
        },
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      this.logger.error('模拟下单测试失败:', error);
      return {
        success: false,
        message: '模拟下单测试失败: ' + error.message,
        timestamp: new Date().toISOString(),
      };
    }
  }
}
